<?php
/**
 * Short Description  
 *
 * Long Description 
 *
 * @category   Core
 * @package    Core_Log
 * @copyright  Costrategix Technologies 
 * @author     Sandeep Manne<sandeep.manne@costrategix.com>
 */

/**
 * 
 * Usage:
 * Just call anywhere in the application
 * Core_Log::log("Log Message", Zend_Log::INFO, array($objectsToTrace));
 *
 */

class Core_Log
{
	/**
	 * Logs any information
	 * 
	 * @param string $text     - Text to be logged
	 * @param string $type     - set type of log (info, warning)
	 * @param mixed  $variable - Any variable to be added to logged
	 * @param string $path     - Log file path / if null default path is taken
	 */
	public static function log($text, $type = Zend_Log::INFO, $variable = null, $path = null)
    {
    	if (!$path) $path = App::getPath('logs') . 'log.txt';
    	//Intializing logger
    	self::initializeLogger($path);
    	$debugInfo = debug_backtrace();
    	
    	//Dumping contents of variable
    	ob_start(); 
    		var_dump($variable); 
    		$dump = ob_get_contents(); 
    	ob_end_clean();
    	
    	try {
            require_once 'Zend/Log/Writer/Stream.php';
            $writer = new Zend_Log_Writer_Stream($path);
            $logger = new Zend_Log($writer);
            //Limiting the dump output to 3000 char to avoid huge log files and memory errors
            $logger->log($text . ' in '. $debugInfo[0]['file'] . ' at line ' . $debugInfo[0]['line']
                          .'\n', $type);
        } catch (Exception $e) {
            Zend_Debug::dump($e->getMessage()); die;
        }
    }
    
	/**
     * Intialize log file and check whether it is more than 100kb
     *
     * @return boolean
     */
    private static function initializeLogger($path)
    {
    	try {
	    	$filePath = $path;
	        if(fopen($filePath,'a')) {
	            $size = round(filesize($filePath)/1024);
	            //If Size > 100 kb 
	            //backup the old file and create new one
	            if ($size > 100) {
	                copy($filePath,$filePath.'.'.time());
	                unlink($filePath);
	                fopen($filePath,'w');
	            }
	            return true;
	        } else {
	            return false;
	        }
    	} catch (Exception $e) {
    		throw new Exception("Error intializing logger : ". $e->getTraceAsString());
    	}
    }
}